<template>
  <div class="data-list-container" v-loading="loading">
    <div class="search-toolbar">
      <el-row :gutter="24">
        <el-col :span="7" style="display: flex; align-items: center">
          <span>申请标题</span>
          <el-input
            style="width: 200px; margin-left: 16px"
            v-model="keyword"
            placeholder="请输入申请标题"
            clearable
            @keyup.enter="fetchData"
            @clear="fetchData"
          />
        </el-col>
        <el-col :span="7" style="display: flex; align-items: center">
          <span>申请节点</span>
          <el-select
            style="width: 200px; margin-left: 16px"
            v-model="nodeCode"
            placeholder="请选择节点"
            clearable
            @keyup.enter="fetchData"
            @clear="fetchData"
          >
            <el-option label="全部" value="" />
            <el-option label="信息中心经办人审核" value="LEFT_1" />
            <el-option label="信息中心审核人审核" value="LEFT_2" />
            <el-option label="信息中心分管领导审核" value="LEFT_3" />
            <el-option label="数源单位审核" value="RIGHT" />
            <el-option label="科信处选择审核人" value="DEPT_SELECT" />
            <el-option label="科信处多人审核" value="DEPT_AUDIT" />
            <el-option label="科信处领导审核" value="LEADER_AUDIT" />
            <el-option label="信息中心通知" value="NOTIFY" />
          </el-select>
        </el-col>
        <el-col :span="7" style="display: flex; align-items: center">
          <span>申请类型</span>
          <el-select
            style="width: 200px; margin-left: 16px"
            v-model="type"
            placeholder="请选择类型"
            clearable
            @keyup.enter="fetchData"
            @clear="fetchData"
          >
            <el-option label="全部" value="" />
            <el-option label="ETL" value="1" />
            <el-option label="数据集" value="2" />
            <el-option label="数据接口" value="3" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <div class="search-button" @click="fetchData">
            <el-button type="primary" style="background-color: #009eff; border-color: #009eff"
              >搜索</el-button
            >
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="result-sort-container">
      <div class="result-count">
        共有<span class="result-count-number">
          {{ total }}
        </span>
        个申请
      </div>
    </div>

    <div class="data-cards-container">
      <template v-if="tableData.length > 0">
        <div v-for="item in tableData" :key="item.id" class="data-card-item">
          <div class="card-header">
            <div class="card-header-content">
              <span class="card-title">{{ item.applicationTitle }}</span>
            </div>
            <div class="card-actions">
              <el-button link @click="handlePreview(item)" type="primary">查看详情</el-button>
              <el-button
                v-if="
                  item.nodeCode === 'LEFT_1' ||
                  item.nodeCode === 'LEFT_2' ||
                  item.nodeCode === 'LEFT_3' ||
                  item.nodeCode === 'RIGHT' ||
                  item.nodeCode === 'LEADER_AUDIT' ||
                  item.nodeCode === 'DEPT_AUDIT'
                "
                link
                type="danger"
                @click="handleAudit(item)"
              >
                审批
              </el-button>
              <el-button
                v-if="item.nodeCode === 'DEPT_SELECT'"
                link
                type="danger"
                @click="handleSetAuditor(item)"
              >
                设置审批人
              </el-button>
            </div>
          </div>

          <div class="card-tags">
            <el-tag style="margin-left: 6px; background-color: #ecf5ff">{{
              getItemType(item.applicationType)
            }}</el-tag>
          </div>

          <div class="card-summary">申请原因：{{ item.applicationReason }}</div>

          <div class="card-footer">
            <div class="info-item">
              <img src="@/assets/imgs/data/time.png" />
              <span>提交时间：{{ formatCreateTime(item.createTime) }}</span>
            </div>

            <div class="info-item" v-if="item.nodeCode">
              <img src="@/assets/imgs/data/view.png" />
              <span>审批节点：{{ getNodeName(item.nodeCode) }}</span>
            </div>
            <div class="info-item">
              <img src="@/assets/imgs/data/view.png" />
              <span
                >状态：
                <span style="color: #409eff" v-if="item.nodeCode === 'NOTIFY'">审批通过</span>
                <span style="color: #ff4949" v-else>审批中</span>
              </span>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="!loading">
        <el-empty description="暂无申请数据" />
      </template>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 40, 80]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="fetchData"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="showDetailDialog" width="1000px" :before-close="handleCloseDetail">
      <el-form :model="detailForm" :rules="formRules" ref="detailFormRef" label-width="150px">
        <el-form-item label="申请标题" prop="applicationTitle">
          <el-input
            v-model="detailForm.applicationTitle"
            placeholder="请输入申请标题"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="申请原因" prop="applicationReason">
          <el-input
            v-model="detailForm.applicationReason"
            type="textarea"
            :rows="3"
            placeholder="请输入申请原因"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="应用场景" prop="applicationScenario">
          <el-input
            v-model="detailForm.applicationScenario"
            type="textarea"
            :rows="2"
            placeholder="请输入数据的应用场景"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="使用时间" prop="useTime">
          <el-date-picker
            v-model="detailForm.useTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input
            v-model="detailForm.contactPhone"
            placeholder="请输入联系电话"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="联系地址" prop="contactAddress">
          <el-input
            v-model="detailForm.contactAddress"
            placeholder="请输入联系地址"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="服务范围" prop="serviceScope">
          <el-input
            v-model="detailForm.serviceScope"
            type="textarea"
            :rows="2"
            placeholder="基于开发数据开发的应用上线之后的用户群体以及对应的服务范围"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="预期成效" prop="expectedEffect">
          <el-input
            v-model="detailForm.expectedEffect"
            type="textarea"
            :rows="2"
            placeholder="基于开放数据开发的应用上线之后的社会效益、经济效益"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input
            v-model="detailForm.systemName"
            placeholder="使用开放数据的业务系统名称"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="部署地点" prop="deploymentLocation">
          <el-input
            v-model="detailForm.deploymentLocation"
            placeholder="使用开放数据的业务系统部署地点/机房地址"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="系统IP" prop="systemIp">
          <el-input
            v-model="detailForm.systemIp"
            placeholder="使用开放数据的业务系统IP"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="系统URL" prop="systemUrl">
          <el-input
            v-model="detailForm.systemUrl"
            placeholder="使用开放数据的业务系统URL地址"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="等保备案编号" prop="levelProtectionCode">
          <el-input
            v-model="detailForm.levelProtectionCode"
            placeholder="使用开放数据的业务系统等级保护备案编号"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="等保级别" prop="levelProtectionLevel">
          <el-select
            v-model="detailForm.levelProtectionLevel"
            placeholder="请选择等保级别"
            :disabled="!isEditing"
          >
            <el-option
              v-for="item in levelProtectionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="承诺书" prop="commitmentFile">
          <UploadFile
            v-model="detailForm.commitmentFile"
            :file-type="['pdf']"
            :file-size="10"
            :limit="1"
            :is-show-tip="true"
            :typeDownload="'1'"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item label="申请书" prop="applyFile">
          <UploadFile
            v-model="detailForm.applyFile"
            :file-type="['pdf']"
            :file-size="10"
            :limit="1"
            :is-show-tip="true"
            :typeDownload="'2'"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item
          v-if="detailForm.applicationType === '1'"
          label="目标数据库地址"
          prop="targetDatabaseAddress"
        >
          <el-input
            v-model="detailForm.targetDatabaseAddress"
            placeholder="请输入目标数据库地址，账号等信息"
            :disabled="!isEditing"
          />
        </el-form-item>
        <el-form-item
          v-if="detailForm.applicationType === '1'"
          label="目标数据库表名"
          prop="targetDatabaseTableName"
        >
          <el-input
            v-model="detailForm.targetDatabaseTableName"
            placeholder="请输入目标数据库表名"
            :disabled="!isEditing"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDetail">取消</el-button>
          <!-- 状态为0时，根据是否编辑状态显示不同按钮 -->
          <template v-if="detailData.status === '0'">
            <template v-if="!isEditing">
              <el-button type="primary" @click="handleEdit">修改</el-button>
            </template>
            <template v-else>
              <el-button type="primary" @click="handleUpdate('1')">提交</el-button>
              <el-button type="primary" @click="handleUpdate('0')">保存</el-button>
            </template>
          </template>
        </span>
      </template>
    </el-dialog>

    <!-- 审批弹窗 -->
    <el-dialog v-model="showAuditDialog" title="审批申请" width="500px">
      <el-form label-width="100px">
        <!-- 添加审批结果下拉框 -->
        <el-form-item label="审批结果" prop="auditResult">
          <el-select v-model="auditResult" placeholder="请选择审批结果" style="width: 100%">
            <el-option label="通过" value="1" />
            <el-option label="不通过" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="auditRemark" type="textarea" :rows="4" placeholder="请输入审批备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAuditDialog = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置审批人弹窗 -->
    <el-dialog v-model="showSetAuditorDialog" title="设置审批人" width="500px">
      <el-form label-width="100px">
        <el-form-item label="选择审批人" prop="auditors">
          <el-select
            v-model="selectedAuditors"
            placeholder="请选择审批人"
            filterable
            multiple
            style="width: 100%"
          >
            <el-option
              v-for="user in auditorList"
              :key="user.id"
              :label="
                user.nickName && user.orgName ? `${user.nickName}(${user.orgName})` : user.name
              "
              :value="user.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="auditorRemark" type="textarea" :rows="4" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSetAuditorDialog = false">取消</el-button>
          <el-button type="primary" @click="submitSetAuditor">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import {
  applicationAuditPage,
  getApplication,
  updateApplication,
  recallApplication,
  deleteApplication,
  applicationAudit,
  setAuditUser
} from '@/api/portal'
import * as portalApi from '@/api/portal'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
import UploadFile from '@/components/UploadFile/src/UploadFile.vue'

const router = useRouter()

// 定义接口返回的数据结构
interface ResourceItem {
  id: number
  catalogId: string
  applicationType: string
  applicationTitle: string
  applicationReason: string
  applicationScenario: string
  useTimeStart: string
  useTimeEnd: string
  contactPhone: string
  contactAddress: string
  serviceScope: string
  expectedEffect: string
  systemName: string
  deploymentLocation: string
  systemIp: string
  systemUrl: string
  levelProtectionCode: string
  levelProtectionLevel: string
  commitmentFile: string
  applyFile: string
  callCountLimit: number | null
  callIntervalSeconds: number | null
  targetDatabaseAddress: string
  targetDatabaseTableName: string
  status: string
  createTime: number
  recordId?: string
  nodeCode?: string
  nodeName?: string
  applicationId?: string
}

// 定义DictOption接口
interface DictOption {
  label: string
  value: string
}

// 搜索筛选参数
const keyword = ref('')
const nodeCode = ref('')
const type = ref('')

// 分页相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref<ResourceItem[]>([])

// 详情弹窗相关
const showDetailDialog = ref(false)
const detailFormRef = ref<FormInstance>()
const detailData = ref<ResourceItem | null>(null)
const isEditing = ref(false)
const levelProtectionOptions = ref<DictOption[]>([
  { label: '一级', value: '1' },
  { label: '二级', value: '2' },
  { label: '三级', value: '3' },
  { label: '四级', value: '4' },
  { label: '五级', value: '5' }
])

// 详情表单数据
const detailForm = reactive({
  applicationType: '1',
  applicationTitle: '',
  applicationReason: '',
  applicationScenario: '',
  useTime: [] as [string, string],
  contactPhone: '',
  contactAddress: '',
  serviceScope: '',
  expectedEffect: '',
  systemName: '',
  deploymentLocation: '',
  systemIp: '',
  systemUrl: '',
  levelProtectionCode: '',
  levelProtectionLevel: '',
  targetDatabaseAddress: '',
  targetDatabaseTableName: '',
  commitmentFile: '',
  applyFile: ''
})

// 表单验证规则
const formRules: FormRules = {
  applicationTitle: [{ required: true, message: '请输入申请标题', trigger: 'blur' }],
  applicationReason: [{ required: true, message: '请输入申请原因', trigger: 'blur' }],
  applicationScenario: [{ required: true, message: '请输入数据的应用场景', trigger: 'blur' }],
  useTime: [{ required: true, message: '请选择使用时间', trigger: 'change' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactAddress: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
  serviceScope: [
    {
      required: true,
      message: '基于开发数据开发的应用上线之后的用户群体以及对应的服务范围',
      trigger: 'blur'
    }
  ],
  expectedEffect: [
    {
      required: true,
      message: '基于开放数据开发的应用上线之后的社会效益、经济效益',
      trigger: 'blur'
    }
  ],
  targetDatabaseAddress: [
    { required: true, message: '请输入目标数据库地址，账号等信息', trigger: 'blur' }
  ],
  targetDatabaseTableName: [{ required: true, message: '请输入目标数据库表名', trigger: 'blur' }],
  commitmentFile: [{ required: true, message: '请上传承诺书', trigger: 'change' }],
  applyFile: [{ required: true, message: '请上传申请书', trigger: 'change' }]
}

// 格式化创建时间
const formatCreateTime = (timestamp: number) => {
  if (!timestamp) return '--'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 添加一个专门处理日期字符串的函数
const formatDateString = (dateString: string) => {
  if (!dateString) return ''
  // 直接截取日期部分，不使用new Date避免时区问题
  if (dateString.includes(' ')) {
    return dateString.split(' ')[0]
  }
  return dateString
}

// 获取申请类型文本
const getItemType = (type: string) => {
  const typeMap = {
    '1': 'ETL',
    '2': '数据集',
    '3': '接口'
  }
  return typeMap[type as keyof typeof typeMap] || '未知'
}

// 获取申请状态文本
const getItemStatus = (status: string) => {
  const statusMap = {
    '0': '待提交',
    '1': '已提交',
    '2': '审核中',
    '3': '审核不通过',
    '4': '审核通过'
  }
  return statusMap[status as keyof typeof statusMap] || '未知'
}

// 获取审批节点文本
const getNodeName = (nodeCode?: string) => {
  if (!nodeCode) return ''

  const nodeMap = {
    LEFT_1: '信息中心经办人审核',
    LEFT_2: '信息中心审核人审核',
    LEFT_3: '信息中心分管领导审核',
    RIGHT: '数源单位审核',
    DEPT_SELECT: '科信处选择审核人',
    DEPT_AUDIT: '科信处多人审核',
    LEADER_AUDIT: '科信处领导审核',
    NOTIFY: '信息中心通知'
  }

  return nodeMap[nodeCode as keyof typeof nodeMap] || nodeCode
}

// 查看详情
const handlePreview = (item: ResourceItem) => {
  // 调用查看详情接口
  getApplication({ id: item.applicationId }).then((res) => {
    if (res) {
      detailData.value = res
      // 填充表单数据
      detailForm.applicationType = res.applicationType
      detailForm.applicationTitle = res.applicationTitle
      detailForm.applicationReason = res.applicationReason
      detailForm.applicationScenario = res.applicationScenario
      detailForm.useTime =
        res.useTimeStart && res.useTimeEnd
          ? [formatDateString(res.useTimeStart), formatDateString(res.useTimeEnd)]
          : []
      detailForm.contactPhone = res.contactPhone
      detailForm.contactAddress = res.contactAddress
      detailForm.serviceScope = res.serviceScope
      detailForm.expectedEffect = res.expectedEffect
      detailForm.systemName = res.systemName
      detailForm.deploymentLocation = res.deploymentLocation
      detailForm.systemIp = res.systemIp
      detailForm.systemUrl = res.systemUrl
      detailForm.levelProtectionCode = res.levelProtectionCode
      detailForm.levelProtectionLevel = res.levelProtectionLevel
      detailForm.targetDatabaseAddress = res.targetDatabaseAddress
      detailForm.targetDatabaseTableName = res.targetDatabaseTableName
      detailForm.commitmentFile = res.commitmentFile
      detailForm.applyFile = res.applyFile

      // 重置编辑状态
      isEditing.value = false
      showDetailDialog.value = true
    } else {
      ElMessage.error('获取详情失败')
    }
  })
}

// 审批弹窗相关
const showAuditDialog = ref(false)
const auditRemark = ref('')
const currentAuditItem = ref<ResourceItem | null>(null)
const auditResult = ref<string>('')

// 添加设置审批人弹窗相关变量
const showSetAuditorDialog = ref(false)
const auditorRemark = ref('')
const selectedAuditors = ref<string[]>([])
const auditorList = ref<any[]>([])
const currentSetAuditItem = ref<ResourceItem | null>(null)

// 处理审批
const handleAudit = (item: ResourceItem) => {
  currentAuditItem.value = item
  auditRemark.value = ''
  auditResult.value = ''
  showAuditDialog.value = true
}

// 处理设置审批人
const handleSetAuditor = async (item: ResourceItem) => {
  currentSetAuditItem.value = item
  auditorRemark.value = ''
  selectedAuditors.value = []

  try {
    // 调用setAuditUser接口获取用户列表
    const response = await setAuditUser()
    if (response && Array.isArray(response)) {
      auditorList.value = response
    } else {
      ElMessage.error('获取审批人列表失败')
    }
  } catch (error) {
    ElMessage.error('获取审批人列表失败')
    console.error('获取审批人列表失败:', error)
  }

  showSetAuditorDialog.value = true
}

// 提交设置审批人
const submitSetAuditor = async () => {
  if (!currentSetAuditItem.value) return

  // 验证是否选择了审批人
  if (selectedAuditors.value.length === 0) {
    ElMessage.warning('请选择审批人')
    return
  }

  try {
    // 准备提交数据，将选中的审批人以逗号分隔的字符串形式传入
    const submitData = {
      applicationId:
        currentSetAuditItem.value.applicationId || currentSetAuditItem.value.id.toString(),
      id: currentSetAuditItem.value.id,
      currentNodeCode: currentSetAuditItem.value.nodeCode || 'DEPT_SELECT',
      remark: auditorRemark.value,
      auditor: selectedAuditors.value.join(','), // 以逗号分隔的字符串形式传入
      auditResult: '1'
    }

    // 调用审批接口
    await applicationAudit(submitData)
    ElMessage.success('设置审批人成功')

    // 关闭弹窗
    showSetAuditorDialog.value = false
    // 刷新列表
    await fetchData()
    await userStore.updateAuditCountAction()
  } catch (error) {
    ElMessage.error('设置审批人失败')
    console.error('设置审批人失败:', error)
  }
}

// 提交审批
const submitAudit = async () => {
  if (!currentAuditItem.value) return

  // 验证审批结果是否填写
  if (!auditResult.value) {
    ElMessage.warning('请选择审批结果')
    return
  }

  try {
    // 准备提交数据，添加completeStatus字段
    const submitData = {
      applicationId: currentAuditItem.value.applicationId || currentAuditItem.value.id.toString(),
      id: currentAuditItem.value.id,
      currentNodeCode: currentAuditItem.value.nodeCode || 'LEFT_1',
      remark: auditRemark.value,
      auditResult: auditResult.value // 添加审批结果
    }

    // 调用审批接口
    await applicationAudit(submitData)
    ElMessage.success('审批提交成功')

    // 关闭弹窗
    showAuditDialog.value = false
    // 刷新列表
    await fetchData()

    await userStore.updateAuditCountAction()
  } catch (error) {
    ElMessage.error('审批提交失败')
    console.error('审批提交失败:', error)
  }
}

// 处理修改
const handleEdit = () => {
  isEditing.value = true
}

// 处理更新
const handleUpdate = async (type: string) => {
  if (!detailFormRef.value || !detailData.value) return

  try {
    await detailFormRef.value.validate()

    // 准备提交数据，根据传入的type设置status值
    const { useTime, ...otherFormData } = detailForm
    const submitData = {
      id: detailData.value.id,
      catalogId: detailData.value.catalogId,
      ...otherFormData,
      useTimeStart: useTime[0],
      useTimeEnd: useTime[1],
      status: type // 直接将传入的type参数作为status值
    }

    // 调用更新接口
    await updateApplication(submitData)

    if (type === '0') {
      ElMessage.success('保存成功')
    } else if (type === '1') {
      ElMessage.success('提交成功')
    }

    // 关闭弹窗
    handleCloseDetail()
    // 刷新列表
    await fetchData()
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  showDetailDialog.value = false
  isEditing.value = false
  // 重置表单
  if (detailFormRef.value) {
    detailFormRef.value.resetFields()
  }
}

// 处理操作（取消申请）
const handleAction = async (item: ResourceItem) => {
  try {
    // 这里应该调用取消申请的接口
    console.log('取消申请', item)
    ElMessage.success('取消申请成功')
    // 刷新列表
    await fetchData()
  } catch (error) {
    ElMessage.error('取消申请失败')
    console.error('取消申请失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 准备请求参数
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      // 添加搜索条件
      applicationTitle: keyword.value,
      nodeCode: nodeCode.value,
      applicationType: type.value
    }

    // 调用接口获取数据
    const res = await portalApi.applicationAuditPage(params)

    // 根据接口返回的数据结构处理
    if (res && res.list) {
      tableData.value = res.list
      total.value = res.total || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取申请列表失败:', error)
    ElMessage.error('获取申请列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  keyword.value = ''
  nodeCode.value = ''
  type.value = ''
  currentPage.value = 1
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.data-list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;

  .search-toolbar {
    margin-bottom: 12px;
  }

  .result-sort-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .result-count {
    font-size: 14px;
    color: #999999;

    .result-count-number {
      font-size: 18px;
      color: #1faaff;
      margin: 0 8px;
    }
  }

  .data-cards-container {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-height: 300px;
    justify-content: center;
    align-items: center;
  }

  // 当有数据时恢复正常布局
  .data-cards-container:has(.data-card-item) {
    justify-content: flex-start;
    align-items: stretch;
  }

  .data-card-item {
    background: #fff url('@/assets/imgs/data/back-data.png') no-repeat center center;
    background-size: cover;
    border-radius: 4px;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    position: relative;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .card-header-content {
        display: flex;
        align-items: center;

        .card-title {
          font-size: 18px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .card-actions {
        display: flex;
        align-items: center;
        gap: 8px;

        .el-button {
          transition: all 0.3s ease;

          &:hover {
            transform: scale(1.05);
          }

          &:active {
            transform: scale(0.95);
          }
        }
      }
    }

    .card-tags {
      margin-bottom: 8px;
    }

    .card-summary {
      font-size: 14px;
      color: #606266;
      line-height: 1.6;
      margin-bottom: 12px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .card-footer {
      font-size: 13px;
      color: #909399;
      display: flex;
      gap: 50px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 4px;

        img {
          width: 16px;
          height: 16px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
